package com.hexun.es.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @description: 数据配置，进行初始化操作
 * @author:yrw
 * @date 2018/11/20
 */
@Configuration
public class EsConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(EsConfiguration.class);

    /**
     * es集群地址
     */
    @Value("${elasticsearch.ip}")
    private String hostName;
    /**
     * 端口
     */
    @Value("${elasticsearch.port}")
    private String port;
    /**
     * 集群名称
     */
    @Value("${elasticsearch.cluster.name}")
    private String clusterName;

    private TransportClient client;

    @Bean
    public TransportClient transportClient() {
        Settings settings = Settings.builder().put("cluster.name", clusterName).build();
        TransportClient client = new PreBuiltTransportClient(settings);
        InetSocketTransportAddress node = null;
        try {
            node = new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        client.addTransportAddress(node);
        return client;
    }

}